<?php

/**
 * @desc: Attachment 
 * 
 * @author: Tran Nghia <nghiat@vnext.vn>
 * @since: 2012/02/29
 * 
 */

class Vlib_Attachment  {

    private $inputFileName = null;
    private $inputOtherFileName = null;
    private $actJsDownload = null;
    private $aryFileUploaded = null;
    private $aryFileInsert = null;
    private $aryFileUpdate = null;
    private $downloadDirKey = null; // key config tham chiếu đến đường dẫn thư mục chưa tệp đính kèm
    private $allowUpdateFilename = null; // Cờ xác định hiển thị cập nhật tên tệp đã tồn tại
    private $showInputAfterDelete = null; // Cờ xác định hiển thị input sau khi xóa
    const DEFAULT_INPUT_FILE_NAME = '添付ファイル名';
    const ERROR_DOWNLOAD_FILE = "ファイルが見つかりません。";
    const FDOC_ERR_EX_OTHER 	= Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
    const FDOC_OK 	= Vlib_Constant::VLIB_OK;
    
    /**
    * @desc: Initialize some variable & Object
    *
    * @author: Tran Nghia <nghiat@vnext.vn>
    * @since: 2012/02/29
    */
    public function __construct() {
        $frontController = Zend_Controller_Front::getInstance();
        $this->_request = $frontController->getRequest();
        $this->_objLogic = new Vlib_Models_Table();
        $this->error = array();
        $this->_logger = Vlib_Logger::getInstance();
    }

    /**
     * @desc: Set error
     *
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
    */
    public function setError($error) {
        $this->error[] = $error;
    }

    /**
     * Get error
     * author: Chungnv@vnext.vn
     * @param string $error
     */
    public function getError() {
        return self::ERROR_DOWNLOAD_FILE;
    }

    /**
     * Clear error
     * author: Chungnv@vnext.vn
     * @param string $error
     */
    public function clearError() {
        $this->error = array();
    }

    /**
     * setFormatView
     *
     * @param string $Priority
     */
    public function setFormatView($type = true) {
        $this->formatView = $type;
    }

    public function getFileForInsert() {
        return $this->aryFileInsert;
    }

    public function getFileForUpdate() {
        return $this->aryFileUpdate;
    }

    /**
     * setWidthView
     *
     * @param string $Priority
     */
    public function setWidthView($width) {
        $this->sizeWidthView = $width;
    }

    /**
     * set name for input type = file
     *
     * @param string $Priority
     */
    public function setInputFileName($str) {
        $this->inputFileName = $str;
    }

    /**
     * set name for input type = text
     * @param <type> $otherFileName
     */
    public function setInputOtherFileName($otherFileName) {
        $this->inputOtherFileName = $otherFileName;
    }

    /**
     * set function js download
     * @param <type> $actJs
     */
    public function setActJsDownload($actJs) {
        $this->actJsDownload = $actJs;
    }
    /**
     * @desc set setDownloadDirKey
     * @author vinhnv@vnext.vn
     */
    public function setDownloadDirKey($key) {
        $this->downloadDirKey = $key;
    }
    /**
     * @desc Có hiển thị cập nhật tên tệp đã tồn tại
     * @param $bool kiểu true/false
     * @author vinhnv@vnext.vn
     */
    public function allowUpdateFilename($bool) {
        $this->allowUpdateFilename = $bool;
    }
    /**
     * @desc Hiển thị input sau khi xóa
     * @param $bool kiểu true/false
     * @author vinhnv@vnext.vn
     */
    public function showInputAfterDelete($bool) {
        $this->showInputAfterDelete = $bool;
    }
    /**
     * Show template default
     *
     * @author Haidm@vnext
     * @since 2010/05/18
     */
    public function actDef() {
        $this->_logger->debugIn();
        $this->_logger->debugOut();
    }

    /**
     * @desc: Check dowload attachment when click button attach on list screen 
     * 
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function checkExistFile($attachmentId, $attachmentDir) {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;

        $aryCondition = array();
        $aryCondition[] = array('', 'attachment_id', '=', $attachmentId);
        $intIsOk = $this->_objLogic->findAttachment($aryCondition, $result);
        $filename = $attachmentDir . '/' . $result['0']['attachment_hash_name'];
        if ($intIsOk == self::FDOC_OK) {
            //Check file exists
            if (file_exists($filename)) {
                $intIsOk = self::FDOC_OK;
            } else {
                $intIsOk = self::ERROR_NOT_FOUND;
            }
        }

        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * @desc: copy attachment
     * 
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
    */
    public function copyAttachment($oldAttachmentId, $attachmentType, $newAttachmentId) {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;
        $intIsOk = $this->_objLogic->getListAttachmentByRelationId($oldAttachmentId, $attachmentType, $aryFileAttachment);
        $inputOtherFileName = $this->inputOtherFileName;
        $listFileNameUpdate = $this->inputFileName . '_update_name';
        $listFileNameDelete = $this->inputFileName . '_delete';
        $strListFileDelete = $this->_request->getParam($listFileNameDelete);
        $aryIdFileDetele = @explode(',', $strListFileDelete);
        $strListAttachmentChange = $this->_request->getParam($listFileNameUpdate);
        $aryAttachmentChangeId = @explode(',', $strListAttachmentChange);
        $aryPostFileName = $this->_request->getParam($inputOtherFileName);
        $index = 0;
        foreach ($aryFileAttachment as $key => $value) {
            if (!@in_array($value['attachment_id'], $aryIdFileDetele)) {
                if (@in_array($value['attachment_id'], $aryAttachmentChangeId)) {
                    $aryFileForCopy[$index]['attachment_filename'] = $aryPostFileName[$value['attachment_id']];
                } else {
                    $aryFileForCopy[$index]['attachment_filename'] = $value['attachment_filename'];
                }
                $aryFileForCopy[$index]['attachment_hash_name'] = $value['attachment_hash_name'];
                $aryFileForCopy[$index]['attachment_file_type'] = $value['attachment_file_type'];
                $aryFileForCopy[$index]['attachment_mime_type'] = $value['attachment_mime_type'];
                $aryFileForCopy[$index]['attachment_file_size'] = $value['attachment_file_size'];
                $index++;
            }
        }
        $this->insertFileAttachForAllModule($aryFileForCopy, $attachmentType, '', $newAttachmentId);
        $this->_logger->debugOut();
    }

    /**
     * @desc hiển thị danh sách tệp đính kèm
     * @param $aryCondtions cung cấp các tham số
     * @author vinhnv@vnext.vn
     * @note một biến thể khác của getListFileAttachment
     * @since 2012/04/11
     */
    public function getAttachments($aryCondtions) {
        $this->_logger->debugIn();
        
        // Khai báo các biến
        $attachment_type = NULL;
        $list = NULL;
        $showButtonDelete = NULL;
        $showIcon = NULL;
        $break = NULL;
        $showExtension = NULL;
        $attachment_issue_code = NULL;
        $attachment_relation_id = NULL;
        $attachment_id = NULL;
        
        // Các tham số được hỗ trợ với giá trị mặc định
        @extract(array(
            'attachment_type' => '',
            'list' => TRUE,
            'showButtonDelete' => TRUE,
            'showIcon' => FALSE,
            'break' => FALSE,
            'showExtension' => TRUE,
            'attachment_issue_code' => NULL,
            'attachment_relation_id' => NULL,
            'attachment_id' => NULL,
        ));
        
        // Xác nhận kiểu dữ liệu
        @is_array($aryCondtions) ? NULL : $aryCondtions = array();
        
        // Lấy ra giá trị thực sự
        @extract($aryCondtions);
        
        // Ra hàm
        $this->_logger->debugOut();
        
        // Gọi hàm thực sự
        return $this->getListFileAttachment(
            $attachment_type,
            $list,
            $showButtonDelete,
            $showIcon,
            $break,
            $showExtension,
            $attachment_issue_code,
            $attachment_relation_id,
            $attachment_id
        );
    }
    /**
     * @desc reset các thuộc tính có vai trò như tham số
     * @author vinhnv@vnext.vn
     * @note một biến thể khác của getListFileAttachment
     * @since 2012/04/11
     */
    private function resetAttributeAsParam() {
        $this->_logger->debugIn();
        
        // Thuộc tính sửa tên tệp
        $this->allowUpdateFilename = NULL;
        // Cờ xác định hiển thị input sau khi xóa
        $this->showInputAfterDelete = NULL;
        
        // Ra hàm
        $this->_logger->debugOut();
    }
    /**
     * @desc: get list file attach to template
     * 
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function getListFileAttachment($attachment_type, $list = true, $showButtonDelete = true, $showIcon = false, $break = false, $showExtension = true, $attachment_issue_code = null, $attachment_relation_id = null, $attachment_id = null) {
        $this->_logger->debugIn();
        
        // Khai báo biến
        $intIsOk = self::FDOC_OK;
        $aryFileAttachment = array();
        $strAttachment = '';
        $javascriptShowInput = '';
        $javascriptShowInput = !empty($this->showInputAfterDelete) ? 'AttachmentController.showInput(\''. $this->inputFileName . '\');' : '';
        
        if ($attachment_id) {
            $intIsOk = $this->_objLogic->getFileAttachment($aryFileAttachment, $attachment_type, null, null, $attachment_id);
        } else {
            $intIsOk = $this->_objLogic->getFileAttachment($aryFileAttachment, $attachment_type, $attachment_issue_code, $attachment_relation_id);
        }
        
        @is_array($aryFileAttachment) ? NULL : $aryFileAttachment = array();
        
        // Chỉ khi thao tác cơ sở dữ liệu thành công và có đính kèm được tìm thấy
        if ($intIsOk == self::FDOC_OK && !empty($aryFileAttachment)) {
            if ($list == true) {
                $aryFileType = array('pdf', 'doc', 'docx', 'xls','csv', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'bmp', 'gif', 'png');
                if($showButtonDelete == true)
                    $strAttachment.='<div id="list_attachment_' . $this->inputFileName . '" class="list-block-attachment">';
                else
                    $strAttachment.='<div class="list-block-attachment">';
                
                foreach ($aryFileAttachment as $key => $value) {
                    $strAttachmentId = '';
                    if($showButtonDelete == true) $strAttachmentId = $value['attachment_id'];
                    $strAttachment.='<div  id="attachment_id_' . $strAttachmentId . '">';
                    
                    if ($showIcon == true) {
                        $value['attachment_file_type'] = strtolower($value['attachment_file_type']);
                        if ($value['attachment_file_type'] == 'pdf') {
                            $strAttachment.='<div class="att-icon pdf fleft"></div>';
                        }
                        if ($value['attachment_file_type'] == 'doc' || $value['attachment_file_type'] == 'docx') {
                            $strAttachment.='<div class="att-icon doc fleft"></div>';
                        }
                        if ($value['attachment_file_type'] == 'xls' || $value['attachment_file_type'] == 'xlsx') {
                            $strAttachment.='<div class="att-icon xls fleft"></div>';
                        }
                        if ($value['attachment_file_type'] == 'ppt' || $value['attachment_file_type'] == 'pptx') {
                            $strAttachment.='<div class="att-icon ppt fleft"></div>';
                        }
                        if ($value['attachment_file_type'] == 'jpg' || $value['attachment_file_type'] == 'jpeg' ||
                                $value['attachment_file_type'] == 'bmp' || $value['attachment_file_type'] == 'gif'
                                || $value['attachment_file_type'] == 'png') {
                            $strAttachment.='<div class="att-icon img fleft"></div>';
                        }

                        if (!@in_array($value['attachment_file_type'], $aryFileType)) {
                            $strAttachment.='<div class="att-icon nofile fleft"></div>';
                        }
                    }
                    // Nếu cờ cho phép hiển thị cập nhật tên tệp thì thêm input vào
                    !empty($this->allowUpdateFilename) ? $strAttachment.='<input type="text" class="fleft textInput" name=' . $this->inputOtherFileName . '_new_name[' . $value['attachment_id'] .']' . ' />' : NULL;
                    if ($showExtension == true) {
                        $strAttachment.='<div class="fleft file-list" title="' . $value['attachment_filename'] . '.' . $value['attachment_file_type'] . '"><a onclick="' . $this->actJsDownload . '(' . $value['attachment_id'] . (!empty($this->downloadDirKey) ? ", '{$this->downloadDirKey}'" : '') . ')">' . htmlspecialchars($value['attachment_filename'],ENT_COMPAT, 'UTF-8') . '.' . $value['attachment_file_type'] . '</a></div>';
                    } else {
                        $strAttachment.='<div class="fleft file-list" title="' . $value['attachment_filename'] . '"><a onclick="' . $this->actJsDownload . '(' . $value['attachment_id']. (!empty($this->downloadDirKey) ? ", '{$this->downloadDirKey}'" : '')   . ')">' . htmlspecialchars($value['attachment_filename'],ENT_COMPAT, 'UTF-8') . '</a></div>';
                    }
                    if ($showButtonDelete == true) {
                        $strAttachment.='<div class="fleft"><span class="att-icon delfile" onclick="AttachmentController.removeInputFileAttach(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "'" . ');' . $javascriptShowInput . '">&nbsp;</span></div>';
                    }
                    $strAttachment.='</div>';
                    $strAttachment .='<div style="clear:both;" ></div>';
                }
                $strAttachment.='</div>';
                
            } else {
                if ($break == true) {
                    $strAttachment.='<div id="list_attachment_' . $this->inputFileName . '" class="list-block-attachment">';
                    foreach ($aryFileAttachment as $key => $value) {
                        $strAttachment.='<div id="attachment_id_' . $value['attachment_id'] . '" class="left-attach">';
                        $strAttachment.='<div><input type="text" class="textInput"  name="' . $this->inputOtherFileName . '[' . $value['attachment_id'] . ']" value="' . $value['attachment_filename'] . '" onchange="AttachmentController.setListFileUpdate(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "_update_name'" . ');" ></div>';
                        $strAttachment.='<div><input type="file" class="fileInput" name="' . $this->inputFileName . '[' . $value['attachment_id'] . ']" onchange="AttachmentController.setListFileUpdate(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "_update'" . ')">';
                        if ($showButtonDelete == true) {
                            $strAttachment.='<input type="button" class="att-button-del fright" value="削除" onclick="AttachmentController.removeInputFileAttach(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "'" . ');' . $javascriptShowInput . '" />';
                        }
                        $strAttachment.='</div>';

                        $strAttachment.='</div>';
                        $strAttachment .='<div class="clear"></div>';
                    }
                    $strAttachment.='</div>';
                    
                } else {
                    $strAttachment.='<div id="list_attachment_' . $this->inputFileName . '" class="list-block-attachment">';
                    foreach ($aryFileAttachment as $key => $value) {
                        $strAttachment.='<div class="left-attach" id="attachment_id_' . $value['attachment_id'] . '">';
                        $strAttachment.='<input type="text" class="textInput ' . $this->inputOtherFileName . '" name="' . $this->inputOtherFileName . '[' . $value['attachment_id'] . ']" value="' . $value['attachment_filename'] . '" onchange="AttachmentController.setListFileUpdate(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "_update_name'" . ');" >';
                        $strAttachment.='<input type="file" class="fileInput ' . $this->inputFileName . '" name="' . $this->inputFileName . '[' . $value['attachment_id'] . ']" onchange="AttachmentController.setListFileUpdate(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "_update'" . ')">';
                        if ($showButtonDelete == true) {
                            $strAttachment.='<input type="button" class="att-button-del fright" value="削除" onclick="AttachmentController.removeInputFileAttach(' . $value['attachment_id'] . ', ' . "'" . $this->inputFileName . "'" . ');' . $javascriptShowInput . '" />';
                        }
                        $strAttachment.='</div>';
                        $strAttachment .='<div class="clear"></div>';
                    }
                    $strAttachment.='</div>';
                    
                }
            }
            if ($showButtonDelete == true) {
                $strAttachment.='<input type="hidden" id="' . $this->inputFileName . '_delete" name="' . $this->inputFileName . '_delete"/>';
                $strAttachment.='<input type="hidden" id="' . $this->inputFileName . '_update" name="' . $this->inputFileName . '_update"/>';
                $strAttachment.='<input type="hidden" id="' . $this->inputFileName . '_update_name" name="' . $this->inputFileName . '_update_name"/>';
            }    
        }

        // reset các thuộc tính có vai trò như tham số
        $this->resetAttributeAsParam();
        
        // Ra hàm
        $this->_logger->debugOut();
        
        return $strAttachment;
    }

    /**
     * @desc: Do dowload attachment when click button attach on list screen
     * 
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function actWapDownloadFile(){
        $this->_logger->debugIn();
        
        $attachmentId = (int) $this->_request->getParam('attachment_id');
        $attachmentDir = $this->_request->getParam('attachment_dir');
        $this->downloadFile($attachmentId, $attachmentDir);

        $this->_logger->debugOut();
    }
    public function downloadFile($attachmentId, $attachmentDir) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_OK;

        $aryCondition = array();
        $aryCondition['attachment_id'] = $attachmentId;
        $this->_objLogic->findAttachment($aryCondition, $result);

        if(count($result) == 0){
            $this->_logger->debugOut();
            return Vlib_Constant::VLIB_ERR_EX_OTHER;
        }
        $fileName = $result['0']['attachment_filename'] . '.' . $result['0']['attachment_file_type'];
        $vlibCommon = Vlib_Common::getInstance();
        
        $fileName = $vlibCommon->UTF8toShiftJIS($fileName);
        
        $fileType = $result['0']['attachment_mime_type'];
        $filepath = $attachmentDir . '/' . $result['0']['attachment_hash_name'];

        //do download
        $fHandle = @fopen($filepath, 'rb');
        if (!$fHandle) {
            $intIsOk = Vlib_Constant::VLIB_ERR_VALIDATION;
        } else {
            // Prepare headers
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            header("Content-Description: File Transfer");
            header("Content-Type: $fileType");
            header("Content-length: " . filesize($filepath));
            header("Accept-Ranges: bytes");
            header("Content-Disposition: attachment; filename=\"" . strip_tags($fileName) . "\";");
            header("Content-Transfer-Encoding: binary");
            // set Size for file
            $size = 1024 * 8;
            
            // Check handle
            while (!feof($fHandle)) {
                $buffer = fgets($fHandle, $size);
                echo $buffer;
            }
            // Close handle
            fclose($fHandle);
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * @desc: Do dowload attachment when click button attach on list screen
     *
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function checkDownloadFile($attachmentId, $attachmentDir) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_OK;

        $aryCondition = array();
        $aryCondition['attachment_id'] = $attachmentId;
        $intIsOk = $this->_objLogic->findAttachment($aryCondition, $result);
        // quynhcv : Test file not found
        if(count($result) == 0){
            $this->_logger->debugOut();
            return Vlib_Constant::VLIB_ERR_EX_OTHER;
        }
        $fileName = $result['0']['attachment_filename'] . '.' . $result['0']['attachment_file_type'];
//        $fileName = $this->UTF8toShiftJIS($fileName);
        $fileType = $result['0']['attachment_mime_type'];
        $filepath = $attachmentDir . '/' . $result['0']['attachment_hash_name'];
        //do download
        $fHandle = fopen($filepath, 'rb');
        if (!$fHandle) {
            $intIsOk = Vlib_Constant::VLIB_ERR_VALIDATION;
        } else {
            $intIsOk = Vlib_Constant::VLIB_OK;
           
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * @desc:  upload file 
     *
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function uploadFile($dirUpload, $fileSizeLimit, $checkType = null,$enCode=true) {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;
        $fieldName = $this->inputFileName;
        $this->aryFileUploaded = array();
        $this->aryFileInsert = array();
        
        $aryFile = array();
        $aryTempFile = array();
        $aryFileType = array();
        $aryFileSize = array();
        if(isset($_FILES[$fieldName]['name']))
            $aryFile = $_FILES[$fieldName]['name'] ;
        if(isset($_FILES[$fieldName]['tmp_name']))
            $aryTempFile = $_FILES[$fieldName]['tmp_name'] ;
        if(isset($_FILES[$fieldName]['type']))
            $aryFileType = $_FILES[$fieldName]['type'] ;
        if(isset($_FILES[$fieldName]['size']))
            $aryFileSize = $_FILES[$fieldName]['size']; 

        if (isset($checkType) && (trim($checkType) != '')) {
            foreach ($aryFile as $key => $value) {
                if (substr($value, strripos($value, '.') + 1) != $checkType) {
                    $intIsOk = 0;
                    break;
                }
            }
        }
        
        //Validate file size
        if(is_array($aryFileSize)) {
            foreach ($aryFileSize as $key => $fileSize) {
                if ($fileSize > $fileSizeLimit) {
                    $intIsOk = self::FDOC_ERR_EX_OTHER;
                }
            }
        }    
        // Check url
        if (substr($dirUpload, -1, 1) != DIRECTORY_SEPARATOR)
            $dirUpload .= DIRECTORY_SEPARATOR;
        @mkdir($dirUpload, 0777, true);
        // Check file
        if (($intIsOk == self::FDOC_OK) && is_array($aryFile) && count($aryFile) > 0) {
            $fileUpload = array();
            foreach ($aryFile as $key => $fileName) {
                // Check isUpload
                if (is_uploaded_file($aryTempFile[$key]) && is_file($aryTempFile[$key])) {
                    if($enCode)
                        $realFileName = number_format(microtime(true), 4, '','') . md5($fileName) . '.fdoc';
                    else
                        $realFileName = $fileName;
//                    $realFileName = number_format(microtime(true), 4, '', '') . md5($fileName) . '.fdoc';
                    // Check copy file to folder
                    if (copy($aryTempFile[$key], $dirUpload . $realFileName)) {

                        // Get data to fileUpload
                        $fileUpload[$key]["attachment_filename"] = substr($fileName, 0, strripos($fileName, '.'));
                        $fileUpload[$key]["attachment_hash_name"] = $realFileName;
                        $fileUpload[$key]["attachment_file_type"] = substr($fileName, strripos($fileName, '.') + 1);
                        $fileUpload[$key]["attachment_file_size"] = (int) $aryFileSize[$key];
                        $fileUpload[$key]["attachment_mime_type"] = $aryFileType[$key];
                    }
                }
            }
            // Return file upload to result
            $this->aryFileUploaded = $fileUpload;
        }
        
        $this->getFileInsertAndUpdate();
        // Log function
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * @desc:  upload file 2
     *
     * @author: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/02/29
     */
    public function uploadFileWithOriginName($dirUpload, $fileSizeLimit, &$fileUploadedUrl, $module, $checkType = null) {
        $this->_objLog->debugIn();
        $intIsOk = self::FDOC_OK;
        $fieldName = $this->inputFileName;
        
        $aryFile = $_FILES[$fieldName]['name'] ;
        $aryTempFile = $_FILES[$fieldName]['tmp_name'] ;
        $aryFileType = $_FILES[$fieldName]['type'] ;
        $aryFileSize = $_FILES[$fieldName]['size']; 
        
        //ThanhDH: check type $aryFile
        if (isset($checkType) && (trim($checkType) != '')) {
            foreach ($aryFile as $key => $value) {
                if (substr($value, strripos($value, '.') + 1) != $checkType) {
                    $intIsOk = 0;
                    break;
                }
            }
        }
        //Validate file size
        foreach ($aryFileSize as $key => $fileSize) {
            if ($fileSize > $fileSizeLimit) {
                $intIsOk = self::FDOC_ERR_EX_OTHER;
            }
        }
        // Check url
        if (substr($dirUpload, -1, 1) != DIRECTORY_SEPARATOR)
            $dirUpload .= DIRECTORY_SEPARATOR;
        @mkdir($dirUpload, 0777, true);
        // Check file
        if (($intIsOk == self::FDOC_OK) && is_array($aryFile) && count($aryFile) > 0) {
            $fileUpload = array();
            foreach ($aryFile as $key => $fileName) {
                // Check isUpload
                if (is_uploaded_file($aryTempFile[$key]) && is_file($aryTempFile[$key])) {
                    // Check copy file to folder
                    if (@copy($aryTempFile[$key], $dirUpload . $fileName)) {
                        $rootPage = $this->_conf['root_page'];
                        $uploadedUrl = $rootPage . "/images/$module/uploads/$fileName";
                        $fileUploadedUrl[$key]["url"] = $uploadedUrl;
                    }
                }
            }
        }
        // Log function
        $this->_logger->debugOut();
        return $intIsOk;
    }

    public function getFileInsertAndUpdate() {
        $this->_logger->debugIn();
        $aryFileUploaded = array();
        $aryFileUploaded = $this->aryFileUploaded;

        $strFileUpdateId = array();
        $strFileUpdateId = $this->_request->getParam($this->inputFileName . '_update');
        $aryInputFileName = array();
        $aryInputFileName = $this->_request->getParam($this->inputOtherFileName);
        if(!$aryInputFileName)$aryInputFileName = array();
        
        if (strlen($strFileUpdateId) > 0) {
            $aryFileUpdateId = @explode(',', $strFileUpdateId);
        }

        $aryFileForInsert = array();
        $aryFileUpdate = array();
        if(is_array($aryFileUploaded)){
            foreach ($aryFileUploaded as $key => $fileUpload) {
                if (@in_array($key, $aryFileUpdateId)) {
                    if (array_key_exists($key,$aryInputFileName) && strlen($aryInputFileName[$key]) > 0 && $aryInputFileName[$key] != self::DEFAULT_INPUT_FILE_NAME) {
                        $aryFileUpdate[$key]["attachment_filename"] = $aryInputFileName[$key];
                    } else {
                        $aryFileUpdate[$key]["attachment_filename"] = $aryFileUploaded[$key]['attachment_filename'];
                    }
                    $aryFileUpdate[$key]["attachment_hash_name"] = $aryFileUploaded[$key]['attachment_hash_name'];
                    $aryFileUpdate[$key]["attachment_file_type"] = $aryFileUploaded[$key]['attachment_file_type'];
                    $aryFileUpdate[$key]["attachment_file_size"] = $aryFileUploaded[$key]['attachment_file_size'];
                    $aryFileUpdate[$key]["attachment_mime_type"] = $aryFileUploaded[$key]['attachment_mime_type'];
                } else {
                    $aryFile = array();
                    if (array_key_exists($key,$aryInputFileName) && strlen($aryInputFileName[$key]) > 0 && $aryInputFileName[$key] != self::DEFAULT_INPUT_FILE_NAME) {
                        $aryFile["attachment_filename"] = $aryInputFileName[$key];
                    } else {
                        $aryFile["attachment_filename"] = $aryFileUploaded[$key]['attachment_filename'];
                    }
                    $aryFile["attachment_hash_name"] = $aryFileUploaded[$key]['attachment_hash_name'];
                    $aryFile["attachment_file_type"] = $aryFileUploaded[$key]['attachment_file_type'];
                    $aryFile["attachment_file_size"] = $aryFileUploaded[$key]['attachment_file_size'];
                    $aryFile["attachment_mime_type"] = $aryFileUploaded[$key]['attachment_mime_type'];
                    $aryFileForInsert[] = $aryFile;
                }
            }
        }


        $this->aryFileInsert = $aryFileForInsert;
        $this->aryFileUpdate = $aryFileUpdate;

        $this->_logger->debugOut();
    }

    /**
     * insert file attach for all module
     * @author cuongvm@vnext.vn
     * @param <type> $listFile get from AttachmentController->uploadFile()
     * @param <type> $attachment_type
     * @param <type> $attachment_issue_code if no issue code set empty
     * @param <type> $attachment_relation_id if no relation_id set empty
     * @return <$intIsOk>
     */
    public function insertFileAttachForAllModule($resultFileUpLoaded, $attachment_type, $attachment_issue_code = null, $attachment_relation_id = null, &$newId = null) {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;
        $row = array();
        
        $row['attachment_type'] = $attachment_type;
        if (isset($attachment_issue_code) && trim($attachment_issue_code) != '') {
            $row['attachment_issue_code'] = $attachment_issue_code;
        }
        if (isset($attachment_relation_id) && trim($attachment_relation_id) != '') {
            $row['attachment_relation_id'] = $attachment_relation_id;
        }
        $row['attachment_created_date'] = date('Y-m-d');
        $row['attachment_updated_date'] = date('Y-m-d');
        $objLogin = Zend_Auth::getInstance()->getStorage()->read();
        $row['attachment_creator_id'] = $objLogin->member_id;
        $row['attachment_updater_id'] = $objLogin->member_id;
        $intIsOk = $this->_objLogic->insertFileAttachmentList($resultFileUpLoaded, $row, $newId);
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * removed file attach
     * @author cuongvm@vnext.vn
     * @param <type> $strDeleteId
     * @return <type>
     */
    public function removeFileAttachment() {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;
        $strDeleteId = $this->_request->getParam($this->inputFileName . '_delete');
        if ($strDeleteId) {
            $aryDeleteID = @explode(',', $strDeleteId);
            for ($i = 0; $i < count($aryDeleteID); $i++) {
                if ((int) $aryDeleteID[$i] != 0) {
                    $this->_objLogic->deleteFile($aryDeleteID[$i]);
                }
            }
        }

        // End Log
        $this->_logger->debugOut();
        return $intIsOk;
    }
    /**
     * @desc cập nhật tên tệp đã có nếu có thể
     * @author vinhnv@vnext.vn
     * @result cập nhật thành công những tệp có tên mới hợp lệ
     */
    public function updateAttachmentName() {
        $this->_logger->debugIn(); // vào hàm
        
        // Khởi tạo biến
        $intIsOk = self::FDOC_OK;
        
        // Lấy ra những id attachment cập nhật tên
        $newNames = $this->_request->getParam($this->inputOtherFileName . '_new_name');
        // Đảm bảo chắc chắn là mảng
        @is_array($newNames) ? NULL : $newNames = array();
        
        foreach($newNames as $attachmentId => $attachmentName) {
            if(empty($attachmentName)) {
                continue;
            }
            $aryCondition = array(
                'attachment_id' => $attachmentId,
                'attachment_filename' => $attachmentName,
            );
            $this->_objLogic->updateAttachment($aryCondition);
        }

        // End Log
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * update file attach in current id
     *
     */
    public function updateFileAttachment($aryFileUpdate) {
        $this->_logger->debugIn();
        $intIsOk = self::FDOC_OK;
        $strListFileNameId = $this->_request->getParam($this->inputFileName . '_update_name');
        if ($strListFileNameId != '' && strlen($strListFileNameId) > 0) {
            $aryIdFileNamUpdate = explode(',', $strListFileNameId);
        }
        $aryFileName = $this->_request->getParam($this->inputOtherFileName);
        if (is_array($aryFileName)) {
            foreach ($aryFileName as $key => $attachId) {
                if (@in_array($key, $aryIdFileNamUpdate)) {
                    $aryFileNameUpdate['attachment_filename'] = $aryFileName[$key];
                    $intIsOk = $this->_objLogic->updateAttachmentById($key, $aryFileNameUpdate);
                }
            }
        }
        if (is_array($aryFileUpdate)) {
            foreach ($aryFileUpdate as $key => $value) {
                $intIsOk = $this->_objLogic->updateAttachmentById($key, $value);
            }
        }
        // End Log
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * Show add file attach
     * @author chungnv@vnext.vn
     * @param $otherInputFileName Cờ xác định có cho phép nhập tên khác cho tệp không
     * @param $break Cờ xác định hiển thị trên nhiều dòng hay một dòng
     * @param $multiFile Cờ xác định cho phép nhập nhiều tệp
     * @param $hide Cờ xác định có hiển thị trên màn hình hay không
     * @return <type>
     */
    public function showInputAddAttachment($otherInputFileName = false, $break = false, $multiFile = true, $hide = false) {
        $this->_logger->debugIn();
        $inputFileName = $this->inputFileName;
        $inputOtherFileName = $this->inputOtherFileName;
        $str = '';
        // Cho phép nhập tệp và tên khác ngoài tên gốc
        if ($otherInputFileName == true) {
            // Hiển thị trên nhiều dòng
            if ($break == true) {
                $str .= '<div id="' . $inputFileName . '"  class="list-block-attachment" style="' . ($hide ? ' display: none; ' : '') .  '" >
                                <div id="' . $inputOtherFileName . '_div_0" class="divAttach"><input id="' . $inputOtherFileName . '_0" type="text" name="' . $inputOtherFileName . '[]' . '" class="textInput" onclick="AttachmentController.clickInputAttachmentNode(this);" onblur="AttachmentController.changeInputAttachmentNode(this);" value="' . self::DEFAULT_INPUT_FILE_NAME . '" /></div>
                                <div id="' . $inputFileName . '_div_0" class="divAttach"><input type="file" id="' . $inputFileName . '_0" name="' . $inputFileName . '[]' . '" class="fileInput" onChange="AttachmentController.onChangeProcessWithDiv(this, ' . "'" . $inputFileName . "'" . ', ' . "'" . $inputOtherFileName . "'" . ');"/></div>
                        </div>';
            }
            // Hiển thị trên một dòng
            else {
                $str .= '<div id="new_' . $this->inputFileName . '" class="list-block-attachment" style="' . ($hide ? ' display: none; ' : '') .  '" >';
                $str .= '<div id="new_div_' . $this->inputFileName . '_0" class="left-attach">';
                $str .= '<input class="textInput" id="' . $inputOtherFileName . '_0" type="text" name="' . $inputOtherFileName . '[]' . '"  onclick="AttachmentController.clickInputAttachmentNode(this);" onblur="AttachmentController.changeInputAttachmentNode(this);" value="' . self::DEFAULT_INPUT_FILE_NAME . '" />';
                $str .= '<input class="fileInput" type="file" id="' . $inputFileName . '_0" name="' . $inputFileName . '[]' . '"  onChange="' . (($multiFile) ? '' : ' return; ') . 'AttachmentController.onChangeProcess(this, ' . "'" . $inputFileName . "'" . ', ' . "'" . $inputOtherFileName . "'" . ');"/>';
                $str .= '</div>';
                $str .= '</div>';
            }
        }
        // Chỉ mỗi tệp
        else {
            $str .= '<table id="' . $inputFileName . '" cellpadding="0" cellspacing="0" class="table-file-attach table-' . $inputFileName . '" style="' . ($hide ? ' display: none; ' : '') .  '" >
                        <tbody>
                        <tr>
                        <td class="td-input-file td_' . $inputFileName . '"><input type="file" name="' . $inputFileName . '[]' . '" class="input-file ' . $inputFileName . '" onChange="' . (($multiFile) ? '' : ' return; ') . 'AttachmentController.onChangeProcessNoInputOtherFileName(' . "'" . $inputFileName . "'" . ');"/></td>
                        </tr>
                        </tbody>
                    </table>';
        }

        return $str;
        // End Log
        $this->_logger->debugOut();
    }

    
}    

